#include "sqlwlisttableview.h"

#include <QContextMenuEvent>
#include <QMenu>
#include <QAction>
#include <QHeaderView>

SqlWlistTableView::SqlWlistTableView(QWidget *parent) :
    contextMenu(new QMenu(this)),
    QTableView(parent)
{
    init();
}

void SqlWlistTableView::init()
{
    setContextMenuPolicy(Qt::DefaultContextMenu);
    setTextElideMode(Qt::ElideNone);
    setEditTriggers(QAbstractItemView::NoEditTriggers);
    setSelectionBehavior(QAbstractItemView::SelectRows);
    setSelectionMode(QAbstractItemView::SingleSelection);
    horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);
    setSortingEnabled(true);

    newPatientAction = contextMenu->addAction(tr("New Patient"), this, SLOT(onNewPatient()));
    newStudyAction = contextMenu->addAction(tr("New Study"), this, SLOT(onNewStudy()));
    changeStudyAction = contextMenu->addAction(tr("Change Study"), this, SLOT(onChangeStudy()));
    removeStudyAction = contextMenu->addAction(tr("Remove Study"), this, SLOT(onRemoveStudy()));
    connect(this, SIGNAL(activated(QModelIndex)), this, SIGNAL(changeStudy(QModelIndex)));
}

void SqlWlistTableView::contextMenuEvent(QContextMenuEvent *e)
{
    QModelIndex index = indexAt(e->pos());
    if (index.isValid()) {
        newStudyAction->setEnabled(true);
        changeStudyAction->setEnabled(true);
        removeStudyAction->setEnabled(true);
    } else {
        newStudyAction->setEnabled(false);
        changeStudyAction->setEnabled(false);
        removeStudyAction->setEnabled(false);
    }

    contextMenu->popup(e->globalPos());
}

void SqlWlistTableView::onNewPatient()
{
    emit newPatient(QModelIndex());
}

void SqlWlistTableView::onNewStudy()
{
    emit newStudy(currentIndex());
}

void SqlWlistTableView::onChangeStudy()
{
    emit changeStudy(currentIndex());
}

void SqlWlistTableView::onRemoveStudy()
{
    emit removeStudy(currentIndex());
}
